package com.example.activity;

import java.util.Iterator;
import java.util.Set;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.R;
import com.example.entity.Capture;
import com.example.entity.CaptureList;
import com.example.entity.SelectMode;
import com.example.entity.ViewHolder;
import com.example.module.linker.FacebookLink;
import com.example.module.linker.KakaoLink;
import com.example.module.linker.TwitterLink;
import com.example.module.switcher.ActivitySwitcher;
import com.example.persistence.SwitchActivity;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;

public class CaptureGridActivity extends SwitchActivity {
	private static final String TAG = "CaptureGridActivity";
	
	private FrameLayout container;
    private GridView gridView;
	private CaptureList captureList;
	private DisplayImageOptions options;

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        enableSwitchAnimation = getIntent().getBooleanExtra(SWITCH_ANIMATION, true);
        
        setContentView(R.layout.activity_capture);
        
        container = (FrameLayout) findViewById(R.id.container);
        gridView = (GridView)findViewById(R.id.gridView);
        wrapContentView(container, gridView);
        
        captureList = application.getCaptureList();
        
        options = new DisplayImageOptions.Builder()
			.showStubImage(R.drawable.icon_100)
			.showImageForEmptyUri(R.drawable.image_for_empty_url)
			.cacheInMemory()
			.cacheOnDisc()
			.build();
        
		gridView.setAdapter(new ImageAdapter());
		gridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				
				if (selectMode == SelectMode.SINGLE)
					selectSingleItem(captureList.get(position).getPath(), view);
				else if (selectMode == SelectMode.MULTIPLE)
					selectMultipleItem(captureList.get(position).getPath(), view);
				else
					startImageGalleryActivity(position);
			}
		});
    }
	
	private void startImageGalleryActivity(int position) {
		Intent intent = new Intent(this, CaptureDetailActivity.class);
		intent.putExtra(IMAGE_POSITION, position);
//		startActivity(intent);
//		switchActivity(intent);
		switchActivityForResult(intent, CAPTURE_DETAIL_CODE);
	}
	
	public class ImageAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return captureList.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = convertView;
			
			if (convertView == null) {
				view = getLayoutInflater().inflate(R.layout.item_grid, parent, false);
			
				ViewHolder viewHolder = new ViewHolder();
				viewHolder.image = (ImageView) view.findViewById(R.id.image);
				viewHolder.text = (TextView) view.findViewById(R.id.text);
				viewHolder.checkOverlay = (FrameLayout) view.findViewById(R.id.checkOverlay);
				view.setTag(viewHolder);
			}
			
			final ViewHolder viewHolder = (ViewHolder) view.getTag();
			viewHolder.text.setText(captureList.get(position).getTitle());
			
			String key = captureList.get(position).getPath();
			viewHolder.selected = isSelectedItem(key);
			viewHolder.checkOverlay.setVisibility(viewHolder.selected ? View.VISIBLE : View.GONE);
			
			String imageFile = captureList.get(position).getThumbnail();
			if (imageFile == null || imageFile.length() < 1)
				imageFile = captureList.get(position).getPath();
			
			imageLoader.displayImage(imageFile, viewHolder.image, options, new SimpleImageLoadingListener() {
				@Override
				public void onLoadingComplete(Bitmap loadedImage) {
					Animation anim = AnimationUtils.loadAnimation(CaptureGridActivity.this, R.anim.fade_in);
					viewHolder.text.setAnimation(anim);
					anim.start();
				}
			});

			return view;
		}
	}
	
	@Override
	protected void shareKakaoTalk(Set<String> selectedItem) {
		if (selectedItem == null || selectedItem.size() < 1)
			return;
		
		KakaoLink kakaoLink = KakaoLink.getLink(getApplicationContext());
		if (!kakaoLink.isAvailableIntent()) {
			alert("Not installed KakaoTalk.");			
			return;
		}
		
		Intent kakaoIntent = null;
		Iterator<String> keys = selectedItem.iterator();
		while (keys.hasNext()) {
			Capture capture = captureList.get(keys.next());
			kakaoIntent = kakaoLink.getIntentForSendImage(capture.getPath());
			break;
		}
		
		deselectAllItems();
		startActivityForResult(kakaoIntent, KAKAO_TALK_CODE);
	}
	
	@Override
	protected void shareTwitter(Set<String> selectedItem) {
		if (selectedItem == null || selectedItem.size() < 1)
			return;
		
		String path = "";
		final StringBuffer message = new StringBuffer();
		
		Iterator<String> keys = selectedItem.iterator();
		while (keys.hasNext()) {
			Capture capture = captureList.get(keys.next());
			path = capture.getPath();
			message.append("사진 공유해요~");
			break;
		}
		
		TwitterLink twitterLink = new TwitterLink(this);
		twitterLink.publish(message.toString(), getLocalFile(path));
	}
	
	@Override
	protected void shareFacebook(Set<String> selectedItem) {
		if (selectedItem == null || selectedItem.size() < 1)
			return;
		
		String path = "";
		StringBuffer message = new StringBuffer();
		
		Iterator<String> keys = selectedItem.iterator();
		while (keys.hasNext()) {
			Capture bookmark = captureList.get(keys.next());
			path = bookmark.getPath();
			message.append("사진 공유해요~");
			break;
		}
		
		FacebookLink facebookLink = new FacebookLink(this);
		facebookLink.publish(message.toString(), getLocalFile(path));
	}
	
	@Override
	protected void doDelete(Set<String> selectedItem) {
		if (selectedItem == null || selectedItem.size() < 1)
			return;
		
		Iterator<String> keys = selectedItem.iterator();
		while (keys.hasNext()) {
			String key = keys.next();
			captureList.removeItem(key);
			deleteLocalFile(key);
		}
		
		((ImageAdapter) gridView.getAdapter()).notifyDataSetChanged();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
		switch (requestCode) {
		case CAPTURE_DETAIL_CODE :
			ActivitySwitcher.animationRightIn(container, getWindowManager());
			break;
		default:
			break;
		}
		
		super.onActivityResult(requestCode, resultCode, data);
	}
}
